/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gisgraph.components;

import edu.uci.ics.jung.graph.DirectedSparseGraph;
import edu.uci.ics.jung.graph.util.EdgeType;
import edu.uci.ics.jung.graph.util.Pair;
import java.util.Collection;
import java.util.Set;
import org.jgrapht.experimental.dag.DirectedAcyclicGraph;
import org.jgrapht.experimental.dag.DirectedAcyclicGraph.CycleFoundException;

/**
 *
 * @author Slawek
 */
public class GraphConverter {
    
    public static DirectedSparseGraph<GISVertex, GISEdge> ConvertToJung(DirectedAcyclicGraph<GISVertex, JGraphEdge> jGraph)
    {
        DirectedSparseGraph<GISVertex, GISEdge> graph = new DirectedSparseGraph<GISVertex, GISEdge>();
        
        Set<GISVertex> vertices = jGraph.vertexSet();
        Set<JGraphEdge> edges = jGraph.edgeSet();
        
        for(GISVertex v : vertices)
        {
            graph.addVertex(v);
        }
        
        for (JGraphEdge e : edges)
        {
            GISVertex source = jGraph.getEdgeSource(e);
            GISVertex target = jGraph.getEdgeTarget(e);
            
            GISEdge edge = new GISEdge(e);
            
            graph.addEdge(edge, source, target, EdgeType.DIRECTED);
        }
        
        return graph;
    }
    
    public static DirectedAcyclicGraph<GISVertex, JGraphEdge> ConvertToJGraph(DirectedSparseGraph<GISVertex, GISEdge> jungGraph) throws CycleFoundException
    {
        DirectedAcyclicGraph<GISVertex, JGraphEdge> graph = 
                new DirectedAcyclicGraph<GISVertex, JGraphEdge>(JGraphEdge.class);
        
        Collection<GISVertex> vertices = jungGraph.getVertices();
        Collection<GISEdge> edges = jungGraph.getEdges();
        
        for(GISVertex v : vertices)
        {
            graph.addVertex(v);
        }
        
        for (GISEdge e : edges)
        {
            Pair<GISVertex> ep = jungGraph.getEndpoints(e);
            GISVertex source = ep.getFirst();
            GISVertex target = ep.getSecond();

            JGraphEdge edge = new JGraphEdge(e);

            graph.addDagEdge(source, target, edge);
        }
        
        return graph;
    }
    
    public static DirectedSparseGraph<StateVertex, GISEdge> ConvertStateGraphToJung(DirectedAcyclicGraph<StateVertex, JGraphEdge> stateGraph)
    {
        DirectedSparseGraph<StateVertex, GISEdge> jungGraph = 
                new DirectedSparseGraph<StateVertex, GISEdge>();
        
        for(StateVertex v : stateGraph.vertexSet())   
        {
            jungGraph.addVertex(v);
        }
        
        for(JGraphEdge e : stateGraph.edgeSet())
        {
            GISEdge edge = new GISEdge(e);

            jungGraph.addEdge(
                            edge, 
                            stateGraph.getEdgeSource(e), 
                            stateGraph.getEdgeTarget(e), 
                            EdgeType.DIRECTED);
        }

        return jungGraph;
    }
}
